<?php
/**
 * 陈杰  18323491246
 */

namespace App\Http\Controllers;

use App\Models\Library\LibraryAnswerModel;
use App\Models\Library\LibraryBuyModel;
use App\Models\Library\LibraryCateModel;
use App\Models\Library\LibraryCommentModel;
use App\Models\Library\LibraryCommentSubModel;
use App\Models\Library\LibraryModel;
use App\Models\Library\LibraryQuestionModel;
use App\Models\Library\LibraryReplyModel;
use App\Models\Library\LibraryRoleModel;
use App\Models\Library\LibraryTopicModel;
use App\Models\MembersModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;


class LibraryController extends Controller
{

    public function roleEdit(Request $request)
    {
        $rules                 = [
            'id'             => 'required|integer|min:1',
            'name'           => 'required|max:25',
            'money_course'   => 'required|numeric|min:0',
            'count_question' => 'required|integer|min:1',
            'money_question' => 'required|numeric|min:0',
        ];
        $sqlmap                = self::checkValidate($rules, $request->all());
        $model                 = LibraryRoleModel::find($sqlmap['id']);
        $model->name           = $sqlmap['name'];
        $model->money_course   = $sqlmap['money_course'];
        $model->count_question = $sqlmap['count_question'];
        $model->money_question = $sqlmap['money_question'];
        try {
            $model->save();
            return self::successMsg();
        } catch (\Exception $exception) {
            return self::errorMsg($exception->getMessage());
        }
    }

    public function roleList(Request $request)
    {
        $data = LibraryRoleModel::get();
        return self::returnMsg($data);
    }

    public function buyList(Request $request)
    {
        $answer_id = (int)$request->input('answer_id');
        $type      = (int)$request->input('type');
        $data      = LibraryBuyModel::where('answer_id', $answer_id)
            ->where('type', $type)
            ->join('member', 'library_buy.member_id', '=', 'member.id')
            ->select('member.name as member_name', 'member.phone as member_phone', 'library_buy.*')
            ->paginate($request->get('count'));
        return self::returnMsg($data);
    }

    public function replyDel(Request $request)
    {
        $id = (int)$request->input('id');
        if ($id < 1)
            return self::errorMsg('请输入正确的回答id');
        if (LibraryReplyModel::where('id', $id)->delete())
            return self::successMsg();
        return self::errorMsg();
    }

    public function replyList(Request $request)
    {
        $firstWhere = function ($query) use ($request) {
            if ($request->has('question_id') and (int)$request->question_id > 0) {
                $query->where('library_reply.question_id', $request->question_id);
            }
        };
        $where      = function ($query) use ($request) {
            //筛选查询关键字
            if ($request->has('keywords') and $request->keywords != '') {
                $keywords = "%" . $request->keywords . "%";
                $query->where('library_reply.id', '=', $request->keywords)
                    ->orWhere('library_reply.member_id', '=', $request->keywords)
                    ->orWhere('member.phone', '=', $request->keywords)
                    ->orWhere('member.name', '=', $request->keywords)
                    ->orWhere('library_answer.topic_id', '=', $request->keywords);
            }
        };
        $order      = 'id';
        if ($request->has('order') and $request->order != '') {
            $order = 'library_reply.' . $request->order;
        }
        $data = LibraryReplyModel::where($firstWhere)
            ->where($where)
            ->join('member', 'library_reply.member_id', '=', 'member.id')
            ->join('library_question', 'library_reply.question_id', '=', 'library_question.id')
            ->orderByDesc($order)
            ->select('library_reply.*', 'member.phone as member_phone', 'member.name as member_name', 'library_question.title as question_title')
            ->paginate($request->get('count'));
        return self::returnMsg($data);
    }

    public function questionDel(Request $request)
    {
        $id = (int)$request->input('id');
        if ($id < 1)
            return self::errorMsg('请输入正确的问题id');
        if (LibraryQuestionModel::where('id', $id)->delete())
            return self::successMsg();
        return self::errorMsg();
    }

    public function questionList(Request $request)
    {
        $where = function ($query) use ($request) {
            //筛选查询关键字
            if ($request->has('keywords') and $request->keywords != '') {
                $keywords = "%" . $request->keywords . "%";
                $query->orWhere('library_question.id', '=', $request->keywords)
                    ->orWhere('library_question.member_id', '=', $request->keywords)
                    ->orWhere('member.phone', '=', $request->keywords)
                    ->orWhere('member.name', '=', $request->keywords);
            }
        };
        $order = 'id';
        if ($request->has('order') and $request->order != '') {
            $order = 'library_question.' . $request->order;
        }
        $data = LibraryQuestionModel::where($where)
            ->join('member', 'library_question.member_id', '=', 'member.id')
            ->select('library_question.*', 'member.name as member_name', 'member.phone as member_phone')
            ->orderByDesc($order)
            ->paginate($request->get('count'));
        return self::returnMsg($data);
    }

    public function commentSubDel(Request $request)
    {
        $id = (int)$request->input('id');
        if ($id < 1)
            return self::errorMsg('请输入正确的回复id');
        if (LibraryCommentSubModel::where('id', $id)->delete())
            return self::successMsg();
        return self::errorMsg();
    }

    public function commentSubList(Request $request)
    {
        $firstWhere = function ($query) use ($request) {
            if ((int)$request->input('comment_id') > 0) {
                $query->where('library_comment_sub.comment_id', (int)$request->input('comment_id'));
            }
        };
        $where      = function ($query) use ($request) {
            //筛选查询关键字
            if ($request->has('keywords') and $request->keywords != '') {
                $keywords = "%" . $request->keywords . "%";
                $query->orWhere('library_comment_sub.id', '=', $request->keywords)
                    ->orWhere('library_comment_sub.member_id', '=', $request->keywords)
                    ->orWhere('member.phone', '=', $request->keywords)
                    ->orWhere('member.name', '=', $request->keywords)
                    ->orWhere('library_comment_sub.comment_id', '=', $request->keywords);
            }
        };
        $order      = 'id';
        if ($request->has('order') and $request->order != '') {
            $order = 'library_comment_sub.' . $request->order;
        }

        $data = LibraryCommentSubModel::where($firstWhere)
            ->where($where)
            ->join('member', 'library_comment_sub.member_id', '=', 'member.id')
            ->select('member.name as member_name', 'member.phone as member_phone', 'library_comment_sub.*')
            ->orderByDesc($order)
            ->paginate($request->get('count'));
        return self::returnMsg($data);
    }

    public function commentList(Request $request)
    {
        $firstWhere = function ($query) use ($request) {
            if ((int)$request->input('pid') > 0 and (int)$request->input('type') > 0) {
                $query->where('library_comment.pid', (int)$request->input('pid'))
                    ->where('library_comment.type', (int)$request->input('type'));
            }
        };
        $where      = function ($query) use ($request) {
            //筛选查询关键字
            if ($request->has('keywords') and $request->keywords != '') {
                $keywords = "%" . $request->keywords . "%";
                $query->orWhere('library_comment.id', '=', $request->keywords)
                    ->orWhere('library_comment.member_id', '=', $request->keywords)
                    ->orWhere('member.phone', '=', $request->keywords)
                    ->orWhere('member.name', '=', $request->keywords)
                    ->orWhere('library_comment.pid', '=', $request->keywords);
            }
        };
        $order      = 'id';
        if ($request->has('order') and $request->order != '') {
            $order = 'library_comment.' . $request->order;
        }

        $data = LibraryCommentModel::where($firstWhere)
            ->where($where)
            ->join('member', 'library_comment.member_id', '=', 'member.id')
            ->select('member.name as member_name', 'member.phone as member_phone', 'library_comment.*')
            ->orderByDesc($order)
            ->paginate($request->get('count'));
        return self::returnMsg($data);
    }

    public function commentDel(Request $request)
    {
        $id = (int)$request->input('id');
        if ($id < 1)
            return self::errorMsg('请输入正确的评论id');
        if (LibraryCommentModel::where('id', $id)->delete())
            return self::successMsg();
        return self::errorMsg();
    }

    public function answerEdit(Request $request)
    {
        $rules = [
            'id'         => 'required|integer|min:1',
            'score'      => 'required|integer|min:1',
            'high_score' => 'required|integer|min:1',
        ];
        $v     = Validator::make($request->all(), $rules);
        if ($v->fails())
            return self::errorMsg($v->errors()->first());
        $sqlmap = $v->validated();

        $model = LibraryAnswerModel::find($sqlmap['id']);
        if (!isset($model))
            return self::errorMsg('没有找到该答案');

        $member = MembersModel::find($model->member_id);
        DB::beginTransaction();
        try {
            if ($sqlmap['high_score'] > 0 and $model->high_score <= 0) {
                //设置为了高分答案
                $topic             = LibraryTopicModel::find($model->topic_id);
                $topic->high_score += 1;
                $topic->save();
            }

            if ($sqlmap['high_score'] <= 0 and $model->high_score > 0) {
                //取消了高分答案
                $topic->high_score -= 1;
                $topic->save();
            }
            if ($member->rank < $model->score) {
                $member->rank = $model->score;
                $member->save();
            }
            $model->score      = $sqlmap['score'];
            $model->high_score = $sqlmap['high_score'];
            $model->status     = 2;
            $model->save();
            DB::commit();
            return self::successMsg();
        } catch (\Exception $exception) {
            DB::rollBack();
            return self::errorMsg($exception->getMessage());
        }
    }

    public function answerDel(Request $request)
    {
        $id = (int)$request->input('id');
        if ($id < 1)
            return self::errorMsg('请输入正确的答案id');
        if (LibraryAnswerModel::where('id', $id)->delete())
            return self::successMsg();
        return self::errorMsg();
    }

    public function answerList(Request $request)
    {
        $firstWhere = function ($query) use ($request) {
            if ($request->has('topic_id') and (int)$request->topic_id > 0) {
                $query->where('library_answer.topic_id', $request->topic_id);
            }
        };
        $where      = function ($query) use ($request) {
            //筛选查询关键字
            if ($request->has('keywords') and $request->keywords != '') {
                $keywords = "%" . $request->keywords . "%";
                $query->where('library_answer.id', '=', $request->keywords)
                    ->orWhere('library_answer.member_id', '=', $request->keywords)
                    ->orWhere('member.phone', '=', $request->keywords)
                    ->orWhere('member.name', '=', $request->keywords)
                    ->orWhere('library_answer.topic_id', '=', $request->keywords);
            }
        };
        $order      = 'id';
        if ($request->has('order') and $request->order != '') {

            if ($request->order == 'verify') {
                $where = function ($query) {
                    return $query->where('library_answer.status', 1);
                };
            } else {
                $order = 'library_answer.' . $request->order;
            }
        }
        $data = LibraryAnswerModel::where($firstWhere)
            ->where($where)
            ->join('member', 'library_answer.member_id', '=', 'member.id')
            ->join('library_topic', 'library_answer.topic_id', '=', 'library_topic.id')
            ->orderByDesc($order)
            ->select('library_answer.*', 'member.phone as member_phone', 'member.name as member_name', 'library_topic.title as topic_title')
            ->paginate($request->get('count'));
        return self::returnMsg($data);
    }

    public function topicEdit(Request $request)
    {
        $rules = [
            'title'      => 'required|max:255',
            //'content'    => 'max:255',
            'cate_id'    => 'required|integer|min:1',
            'library_id' => 'required|integer|min:1',
            'high_score' => 'integer',
        ];
        $v     = Validator::make($request->all(), $rules);
        if ($v->fails())
            return self::errorMsg($v->errors()->first());
        $sqlmap = $v->validated();

        $id = (int)$request->input('id');
        if ($id > 0) {
            //编辑
            $model = LibraryTopicModel::find($id);
            if (!isset($model))
                return self::errorMsg('没有找到该题目');
        } else {
            $model              = new LibraryTopicModel();
            $model->create_time = time();
        }
        $model->title      = $sqlmap['title'];
        //$model->content    = $sqlmap['content'];
        $model->cate_id    = $sqlmap['cate_id'];
        $model->library_id = $sqlmap['library_id'];
        $model->high_score = isset($sqlmap['high_score']) ? $sqlmap['high_score'] : 0;
        try {
            $model->save();
            return self::successMsg();
        } catch (\Exception $exception) {
            return self::errorMsg($exception->getMessage());
        }
    }

    public function topicDel(Request $request)
    {
        $id = (int)$request->input('id');
        if ($id < 1)
            return self::errorMsg('请输入正确的题目id');
        if (LibraryTopicModel::where('id', $id)->delete())
            return self::successMsg();
        return self::errorMsg();
    }

    public function topicList(Request $request)
    {
        $firstWhere = function ($query) use ($request) {
            if ($request->has('library_id') and (int)$request->library_id > 0) {
                $query->where('library_topic.library_id', $request->library_id);
            }
        };
        $where      = function ($query) use ($request) {
            //筛选查询关键字
            if ($request->has('keywords') and $request->keywords != '') {
                $keywords = "%" . $request->keywords . "%";
                $query->orWhere('library_topic.id', '=', $request->keywords)
                    ->orWhere('library_topic.title', 'like', $keywords);
            }

            if ($request->has('cate_id') and (int)$request->cate_id > 0) {
                $query->where('library_topic.cate_id', $request->cate_id);
            }
        };
        $data       = LibraryTopicModel::where($firstWhere)
            ->where($where)
            ->paginate($request->get('count'));
        return self::returnMsg($data);
    }

    public function libraryDel(Request $request)
    {
        $id = (int)$request->input('id');
        if ($id < 1)
            return self::errorMsg('请输入正确的id');
        if (LibraryModel::where('id', $id)->delete())
            return self::successMsg();
        return self::errorMsg();
    }

    public function libraryEdit(Request $request)
    {
        $rules = [
            'name'       => 'required|max:50',
            'image'      => 'max:255',
            'address_id' => 'required|integer|min:1',
            'material'   => 'required|array',
        ];
        $v     = Validator::make($request->all(), $rules);
        if ($v->fails())
            return self::errorMsg($v->errors()->first());
        $sqlmap = $v->validated();

        $id = $request->input('id');
        if ($id > 0) {
            $model = LibraryModel::find($id);
            if (!isset($model))
                self::returnError('没有找到该试卷');
        } else {
            $model = new LibraryModel();
        }
        $model->name        = $sqlmap['name'];
        $model->image       = isset($sqlmap['image']) ? $sqlmap['image'] : null;
        $model->address_id  = $sqlmap['address_id'];
        $model->material    = json_encode($sqlmap['material'], 256);
        $model->create_time = time();

        try {
            $model->save();
            return self::successMsg();
        } catch (\Exception $exception) {
            return self::errorMsg($exception->getMessage());
        }
    }

    /**
     * 卷子列表
     */
    public function libraryList(Request $request)
    {
        $where = function ($query) use ($request) {
            //筛选查询关键字
            if ($request->has('keywords') and $request->keywords != '') {
                $keywords = "%" . $request->keywords . "%";
                $query->orWhere('library.id', '=', $request->keywords)
                    ->orWhere('library.name', 'like', $keywords);
            }
            if ($request->has('address_id') and (int)$request->address_id > 0) {
                $query->where('library.address_id', $request->address_id);
            }
        };
        $data  = LibraryModel::where($where)
            ->join('config_address', 'library.address_id', '=', 'config_address.id')
            ->select('library.*', 'config_address.name as address')
            ->paginate($request->get('count'))
            ->toArray();
        //dd($data);
        foreach ($data['data'] as $k => $v) {
            $data['data'][$k]['material'] = json_decode($v['material'], true);
        }
        return self::returnMsg($data);
    }


    /**
     * 题目类型列表
     */
    public function libraryCateList(Request $request)
    {
        $data = LibraryCateModel::get()->toArray();
        if (!$request->has('all'))
            $data = self::tree($data);
        return self::returnMsg($data);
    }

    public function libraryCateDel(Request $request)
    {
        $id = (int)$request->input('id');
        if ($id < 1)
            return self::errorMsg('请输入正确的id');
        if (LibraryCateModel::where('id', $id)->delete())
            return self::returnMsg();
        return self::errorMsg();
    }

    public function libraryCateEdit(Request $request)
    {
        $rules = [
            'name' => 'required|max:25',
            'pid'  => 'required|integer|min:0',
        ];
        $v     = Validator::make($request->all(), $rules);
        if ($v->fails())
            return self::errorMsg($v->errors()->first());
        $sqlmap = $v->validated();

        $id = $request->input('id');
        if ($id > 0) {
            $model = LibraryCateModel::find($id);
            if (!isset($model))
                self::returnError('没有找到该类型');
        } else {
            $model = new LibraryCateModel();
        }
        $model->name = $sqlmap['name'];
        $model->pid  = $sqlmap['pid'];
        try {
            $model->save();
            return self::successMsg();
        } catch (\Exception $exception) {
            return self::errorMsg($exception->getMessage());
        }
    }

}
